package com.smartao.core.security;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import com.smartao.core.SpringContext;

/**
 * 登录成功后的附加操作接口<br>
 * 继承自{@link SavedRequestAwareAuthenticationSuccessHandler}
 * @author Ricky
 */
public class LoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

	public static final String REMEMBER_PARAM = "rememberMe";
	public static final String COOKIE_KEY = "TEAMS_COOKIE_KEY";
	public static final int MAX_AGE = 3600 * 24 * 14;//默认两周

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws ServletException, IOException {
		postLoginSuccess(request, response, authentication);
		super.onAuthenticationSuccess(request, response, authentication);
	}

	/**
	 * 登录成功后的事件处理接口
	 */
	private void postLoginSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) {
		AuthenticationToken authenticationToken = (AuthenticationToken) authentication;
		SmartaoUser user = (SmartaoUser)authenticationToken.getPrincipal();
		Map<String, PostLoginSuccessHandler> map = SpringContext.getBeans(PostLoginSuccessHandler.class);
		Collection<PostLoginSuccessHandler> handlers = map.values();
		for (PostLoginSuccessHandler handler : handlers) {
			handler.postLoginSuccess(user);
		}
	}

}
